from django.db.models import Q
from rest_framework import mixins, status
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import action

from drf_yasg.utils import swagger_auto_schema

from api.auth import JWTAuthentication, User
from api.routes.advertisement.serializer import (
    AdminProductAdvertisementQeurySerializer,
    AdminProductAdvertisementIDSerializer,
    AdminProductAdvertisementQuerySerializer,
    AdminProductAdvertisementBodySerializer,
    AdvertisementBodySerializer,
)
from api.utils.common import with_common_response, paginate_list

from api.models.advertisement import AdvertiseMent


class AdvertisementViewSet(viewsets.ViewSet):

    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="上传广告图片",
        operation_description="上传广告图片",
        request_body=AdminProductAdvertisementQeurySerializer,
        responses=with_common_response(
            {status.HTTP_202_ACCEPTED: AdminProductAdvertisementIDSerializer}
        ),
    )
    def create(self, request):

        serializer = AdminProductAdvertisementQeurySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        advertisement, _ = AdvertiseMent.objects.update_or_create(
            product=serializer.validated_data.get("product"),
            defaults={"file": serializer.validated_data.get("file")},
        )

        response = AdminProductAdvertisementIDSerializer(advertisement)

        return Response(status=status.HTTP_201_CREATED, data=response.data)

    @swagger_auto_schema(
        operation_summary="首页轮播图片列表",
        operation_description="首页轮播图片列表",
        query_serializer=AdminProductAdvertisementQuerySerializer,
        responses=with_common_response(
            {status.HTTP_202_ACCEPTED: AdminProductAdvertisementBodySerializer}
        ),
    )
    def list(self, request):
        serializer = AdminProductAdvertisementQuerySerializer(data=request.GET)
        serializer.is_valid(raise_exception=True)

        advertise_ment = AdvertiseMent.objects.filter(**serializer.validated_data)

        data, total = paginate_list(data=advertise_ment)

        response = AdvertisementBodySerializer({"total": total, "data": data})

        return Response(status=status.HTTP_200_OK, data=response.data)
